<template>
  <div class="enhanced-permission-form">
    <!-- 字段匹配 -->
    <div v-if="conditionType === 'field_match'" class="form-section">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="用户字段" prop="config.user_field"
            :rules="[{ required: true, message: '请选择用户字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.user_field" placeholder="请选择用户字段" @change="updateConfig" filterable>
              <ElOption v-for="field in userFieldOptions" :key="field.value" :label="field.label" :value="field.value">
                <div>
                  <div>{{ field.label }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.description }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择用户对象中的字段，用于获取匹配值</div>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="目标字段" prop="config.target_field"
            :rules="[{ required: true, message: '请选择目标字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.target_field" placeholder="请选择目标字段" @change="updateConfig" filterable
              :loading="tableFieldsLoading" :disabled="!tableName">
              <ElOption v-for="field in tableFieldOptions" :key="field.column_name" :label="field.display_name"
                :value="field.column_name">
                <div>
                  <div>{{ field.display_name }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.data_type }}{{ field.column_comment ? ` -
                    ${field.column_comment}` : '' }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择数据表中需要匹配的字段</div>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </div>

    <!-- 字段模糊匹配 (LIKE) -->
    <div v-else-if="conditionType === 'field_like'" class="form-section">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="用户字段" prop="config.user_field"
            :rules="[{ required: true, message: '请选择用户字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.user_field" placeholder="请选择用户字段" @change="updateConfig" filterable>
              <ElOption v-for="field in userFieldOptions" :key="field.value" :label="field.label" :value="field.value">
                <div>
                  <div>{{ field.label }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.description }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择用户对象中的字段，用于获取模糊匹配值 (例如: 'some_value%')</div>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="目标字段" prop="config.target_field"
            :rules="[{ required: true, message: '请选择目标字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.target_field" placeholder="请选择目标字段" @change="updateConfig" filterable
              :loading="tableFieldsLoading" :disabled="!tableName">
              <ElOption v-for="field in tableFieldOptions" :key="field.column_name" :label="field.display_name"
                :value="field.column_name">
                <div>
                  <div>{{ field.display_name }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.data_type }}{{ field.column_comment ? ` -
                    ${field.column_comment}` : '' }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择数据表中需要进行模糊匹配的字段</div>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </div>

    <!-- 字段模糊不匹配 (NOT LIKE) -->
    <div v-else-if="conditionType === 'field_not_like'" class="form-section">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="用户字段" prop="config.user_field"
            :rules="[{ required: true, message: '请选择用户字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.user_field" placeholder="请选择用户字段" @change="updateConfig" filterable>
              <ElOption v-for="field in userFieldOptions" :key="field.value" :label="field.label" :value="field.value">
                <div>
                  <div>{{ field.label }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.description }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择用户对象中的字段，用于获取模糊匹配值 (例如: 'some_value%')</div>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="目标字段" prop="config.target_field"
            :rules="[{ required: true, message: '请选择目标字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.target_field" placeholder="请选择目标字段" @change="updateConfig" filterable
              :loading="tableFieldsLoading" :disabled="!tableName">
              <ElOption v-for="field in tableFieldOptions" :key="field.column_name" :label="field.display_name"
                :value="field.column_name">
                <div>
                  <div>{{ field.display_name }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.data_type }}{{ field.column_comment ? ` -
                    ${field.column_comment}` : '' }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择数据表中需要进行模糊匹配的字段</div>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </div>

    <!-- 字段包含列表 -->
    <div v-else-if="conditionType === 'field_in_list'" class="form-section">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="用户列表字段" prop="config.user_list_field"
            :rules="[{ required: true, message: '请选择用户列表字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.user_list_field" placeholder="请选择用户列表字段" @change="updateConfig" filterable>
              <ElOption v-for="field in userListFieldOptions" :key="field.value" :label="field.label"
                :value="field.value">
                <div>
                  <div>{{ field.label }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.description }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择用户对象中包含ID列表的字段</div>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="目标字段" prop="config.target_field"
            :rules="[{ required: true, message: '请选择目标字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.target_field" placeholder="请选择目标字段" @change="updateConfig" filterable
              :loading="tableFieldsLoading" :disabled="!tableName">
              <ElOption v-for="field in tableFieldOptions" :key="field.column_name" :label="field.display_name"
                :value="field.column_name">
                <div>
                  <div>{{ field.display_name }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.data_type }}{{ field.column_comment ? ` -
                    ${field.column_comment}` : '' }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择数据表中需要匹配的字段</div>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </div>

    <!-- 部门列表权限 -->
    <div v-else-if="conditionType === 'dept_list'" class="form-section">
      <ElRow :gutter="20">
        <ElCol :span="12">
          <ElFormItem label="用户部门列表字段" prop="config.user_dept_list_field"
            :rules="[{ required: true, message: '请选择用户部门列表字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.user_dept_list_field" placeholder="请选择用户部门列表字段" @change="updateConfig"
              filterable>
              <ElOption v-for="field in userListFieldOptions" :key="field.value" :label="field.label"
                :value="field.value">
                <div>
                  <div>{{ field.label }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.description }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择用户对象中包含部门ID列表的字段</div>
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="目标部门ID字段" prop="config.target_dept_id_field"
            :rules="[{ required: true, message: '请选择目标部门ID字段', trigger: 'change' }]">
            <ElSelect v-model="localConfig.target_dept_id_field" placeholder="请选择目标部门ID字段" @change="updateConfig"
              filterable :loading="tableFieldsLoading" :disabled="!tableName">
              <ElOption v-for="field in tableFieldOptions" :key="field.column_name" :label="field.display_name"
                :value="field.column_name">
                <div>
                  <div>{{ field.display_name }}</div>
                  <div style="font-size: 12px; color: #909399;">{{ field.data_type }}{{ field.column_comment ? ` -
                    ${field.column_comment}` : '' }}</div>
                </div>
              </ElOption>
            </ElSelect>
            <div class="field-hint">选择数据表中存储部门ID的字段</div>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </div>

    <!-- 自定义SQL -->
    <div v-else-if="conditionType === 'custom_sql'" class="form-section">
      <ElFormItem label="SQL模板" prop="config.sql_template"
        :rules="[{ required: true, message: '请输入SQL模板', trigger: 'blur' }]">
        <ElInput v-model="localConfig.sql_template" type="textarea" :rows="6"
          placeholder="例如: table_alias.user_id = {user.id} AND table_alias.status = 1" @input="updateConfig" />
        <div class="field-hint">
          使用 {user.字段名} 来引用用户信息，table_alias 会被自动替换为实际的表别名
        </div>
      </ElFormItem>

      <!-- 可用用户字段提示 -->
      <ElCollapse>
        <ElCollapseItem title="可用用户字段参考" name="user-fields">
          <div class="user-fields-reference">
            <ElTag v-for="field in userFieldOptions" :key="field.value" class="field-tag">
              {user.{{ field.value }}} - {{ field.label }}
            </ElTag>
          </div>
        </ElCollapseItem>
      </ElCollapse>

      <ElAlert title="安全提示" type="warning" :closable="false" description="自定义SQL具有较高的灵活性，但请确保SQL语句的安全性，避免SQL注入风险" />
    </div>

    <!-- 未知类型 -->
    <div v-else class="form-section">
      <ElAlert title="未知的条件类型" type="error" :closable="false" :description="`不支持的条件类型: ${conditionType}`" />
    </div>

    <!-- 配置预览和测试 -->
    <div class="config-preview-section">
      <ElDivider content-position="left">
        配置预览
      </ElDivider>

      <ElRow :gutter="20">
        <ElCol :span="16">
          <ElInput :model-value="configPreview" type="textarea" :rows="4" readonly placeholder="配置信息将在此显示" />
        </ElCol>
        <ElCol :span="8">
          <div class="preview-actions">
            <ElButton type="success" :icon="Check" @click="validateConfig" :disabled="!isConfigValid">
              验证配置
            </ElButton>
            <ElButton type="primary" :icon="View" @click="showSqlPreview" :disabled="!isConfigValid">
              SQL预览
            </ElButton>
          </div>

          <div v-if="validationResult" class="validation-result">
            <ElAlert :title="validationResult.title" :type="validationResult.type"
              :description="validationResult.message" :closable="false" />
          </div>
        </ElCol>
      </ElRow>
    </div>

    <!-- SQL预览弹窗 -->
    <ElDialog v-model="sqlPreviewVisible" title="SQL预览" width="60%">
      <ElInput :model-value="sqlPreviewContent" type="textarea" :rows="8" readonly
        style="font-family: 'Courier New', monospace;" />
      <template #footer>
        <ElButton @click="sqlPreviewVisible = false">关闭</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
import { View, Check } from '@element-plus/icons-vue'
import { fetchTableColumns, type TableColumnInfo } from '@/api/system/table'

interface Props {
  conditionType: string
  tableName?: string
  modelValue: Record<string, any>
}

interface Emits {
  (e: 'update:modelValue', value: Record<string, any>): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 本地配置对象
const localConfig = ref<Record<string, any>>({})

// 表字段相关
const tableFieldOptions = ref<Array<TableColumnInfo & { display_name: string }>>([])
const tableFieldsLoading = ref(false)

// SQL预览
const sqlPreviewVisible = ref(false)
const sqlPreviewContent = ref('')

// 验证结果
const validationResult = ref<{ title: string, type: 'success' | 'warning' | 'error', message: string } | null>(null)

// 用户字段选项（这里可以根据实际系统的用户模型来定义）
const userFieldOptions = [
  { value: 'id', label: '用户ID', description: '用户的唯一标识符' },
  { value: 'username', label: '用户名', description: '用户登录名' },
  { value: 'name', label: '姓名', description: '用户名称' },
  { value: 'dept_code', label: '部门编码', description: '用户所属部门编码' },
  { value: 'role_ids', label: '角色ID列表', description: '用户拥有的角色ID列表' },
  { value: 'project_ids', label: '项目ID列表', description: '用户可访问的项目ID列表' },
  { value: 'organization_id', label: '组织ID', description: '用户所属组织ID' }
]

// 用户列表字段选项（用于包含列表的权限类型）
const userListFieldOptions = [
  { value: 'role_ids', label: '角色ID列表', description: '用户拥有的角色ID列表' },
  { value: 'project_ids', label: '项目ID列表', description: '用户可访问的项目ID列表' },
  { value: 'dept_ids', label: '部门ID列表', description: '用户可访问的部门ID列表' },
  { value: 'accessible_project_ids', label: '可访问项目列表', description: '用户有权限访问的项目ID列表' },
  { value: 'accessible_dept_ids', label: '可访问部门列表', description: '用户有权限访问的部门ID列表' },
  { value: 'managed_user_ids', label: '管理用户列表', description: '用户可管理的用户ID列表' }
]

// 配置预览
const configPreview = computed(() => {
  try {
    return JSON.stringify(localConfig.value, null, 2)
  } catch {
    return '{}'
  }
})

// 配置是否有效
const isConfigValid = computed(() => {
  return Object.keys(localConfig.value).length > 0 &&
    Object.values(localConfig.value).every(value => value !== '' && value != null)
})

// 加载表字段
const loadTableFields = async (tableName: string) => {
  if (!tableName) {
    tableFieldOptions.value = []
    return
  }

  try {
    tableFieldsLoading.value = true
    const fields = await fetchTableColumns(tableName)
    tableFieldOptions.value = fields.map(field => ({
      ...field,
      display_name: field.column_comment
        ? `${field.column_name} (${field.column_comment})`
        : field.column_name
    }))
  } catch (error) {
    console.error('加载表字段失败:', error)
    ElMessage.error('加载表字段失败')
    tableFieldOptions.value = []
  } finally {
    tableFieldsLoading.value = false
  }
}

// 更新配置
const updateConfig = () => {
  // 清理空值
  const cleanConfig = Object.fromEntries(
    Object.entries(localConfig.value).filter(([_, value]) => value !== '' && value != null)
  )
  emit('update:modelValue', cleanConfig)

  // 清除之前的验证结果
  validationResult.value = null
}

// 显示SQL预览
const showSqlPreview = () => {
  // 这里可以调用后端API生成SQL预览
  // 暂时使用模拟数据
  let sql = ''

  switch (props.conditionType) {
    case 'field_match':
      sql = `SELECT * FROM ${props.tableName} WHERE ${localConfig.value.target_field} = {user.${localConfig.value.user_field}}`
      break
    case 'field_like':
      sql = `SELECT * FROM ${props.tableName} WHERE ${localConfig.value.target_field} LIKE {user.${localConfig.value.user_field}}`
      break
    case 'field_not_like':
      sql = `SELECT * FROM ${props.tableName} WHERE ${localConfig.value.target_field} NOT LIKE {user.${localConfig.value.user_field}}`
      break
    case 'field_in_list':
      sql = `SELECT * FROM ${props.tableName} WHERE ${localConfig.value.target_field} IN ({user.${localConfig.value.user_list_field}})`
      break
    case 'dept_tree':
      sql = `SELECT * FROM ${props.tableName} WHERE ${localConfig.value.target_dept_path_field} LIKE CONCAT({user.dept_path}, '%')`
      break
    case 'dept_list':
      sql = `SELECT * FROM ${props.tableName} WHERE ${localConfig.value.target_dept_id_field} IN ({user.${localConfig.value.user_dept_list_field}})`
      break
    case 'custom_sql':
      sql = localConfig.value.sql_template || ''
      break
  }

  sqlPreviewContent.value = sql
  sqlPreviewVisible.value = true
}

// 验证配置
const validateConfig = () => {
  const config = localConfig.value

  // 基础验证
  if (Object.keys(config).length === 0) {
    validationResult.value = {
      title: '验证失败',
      type: 'error',
      message: '配置信息不能为空'
    }
    return
  }

  // 根据不同类型进行特定验证
  let isValid = true
  let message = '配置验证通过'

  switch (props.conditionType) {
    case 'field_match':
    case 'field_like':
    case 'field_not_like':
      if (!config.user_field || !config.target_field) {
        isValid = false
        message = '用户字段和目标字段都必须选择'
      }
      break
    case 'field_in_list':
      if (!config.user_list_field || !config.target_field) {
        isValid = false
        message = '用户列表字段和目标字段都必须选择'
      }
      break
    case 'dept_tree':
      if (!config.target_dept_path_field) {
        isValid = false
        message = '目标部门路径字段必须选择'
      }
      break
    case 'dept_list':
      if (!config.user_dept_list_field || !config.target_dept_id_field) {
        isValid = false
        message = '用户部门列表字段和目标部门ID字段都必须选择'
      }
      break
    case 'custom_sql':
      if (!config.sql_template) {
        isValid = false
        message = 'SQL模板不能为空'
      } else if (!config.sql_template.includes('{user.')) {
        validationResult.value = {
          title: '验证警告',
          type: 'warning',
          message: 'SQL模板中没有使用用户字段变量，可能无法正确过滤数据'
        }
        return
      }
      break
  }

  validationResult.value = {
    title: isValid ? '验证成功' : '验证失败',
    type: isValid ? 'success' : 'error',
    message
  }
}

// 监听表名变化，加载字段
watch(() => props.tableName, (newTableName) => {
  if (newTableName) {
    loadTableFields(newTableName)
  } else {
    tableFieldOptions.value = []
  }
}, { immediate: true })

// 监听条件类型变化，重置配置 (移除 immediate: true)
watch(() => props.conditionType, (newType) => {
  localConfig.value = {}
  validationResult.value = null
  updateConfig()
})

// 监听外部配置变化
watch(() => props.modelValue, (newValue) => {
  if (newValue && typeof newValue === 'object') {
    // 当外部传入新的对象时，更新本地副本
    localConfig.value = { ...newValue }
  } else if (!newValue) {
    // 如果外部传入 null 或 undefined，则重置
    localConfig.value = {}
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
.enhanced-permission-form {
  .form-section {
    margin-bottom: 24px;
  }

  .field-hint {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
    line-height: 1.4;
  }

  .config-preview-section {

    .validation-result {
      margin-top: 12px;
    }

    :deep(.el-input__inner) {
      font-family: 'Courier New', monospace;
      font-size: 12px;
    }
  }

  .user-fields-reference {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .field-tag {
      font-family: 'Courier New', monospace;
      font-size: 12px;
    }
  }
}
</style>